const mongoConnected = require("../lib/mongoose_connect");
const mongoModels = require("../lib/mongoose_schemas");
const fs = require("fs-extra");
const THREE = require("three");
const lodash = require("lodash");
const path = require("path");

// let match_id = "match.bro.competitive.pc-2018-07.steam.squad-fpp.sa.2020.06.01.02.b1e69002-7f96-409a-843e-f59d434c2eac"
/**
 * 
 * @param {{x:Number,y:Number}} point 
 * @param  {{x:Number,y:Number}}line_p1 
 * @param  {{x:Number,y:Number}}line_p2 
 */
function distanceToLine(point, line_p1, line_p2) {
  let line = new THREE.Line3();
  let P = new THREE.Vector3(point.x, point.y, 0);
  let A = new THREE.Vector3(line_p1.x, line_p1.y, 0);
  let B = new THREE.Vector3(line_p2.x, line_p2.y, 0);
  let C = new THREE.Vector3()
  line.set(A, B);
  line.closestPointToPoint(P, false, C)
  let dis = P.distanceTo(C);
  return dis;
}
mongoConnected.then(async $ => {
  // let d = distanceToLine({ x: 9, y: 3 }, { x: 0, y: 0 }, { x: 1, y: 0 })
  // d = distanceToLine({ x: 3 * Math.sqrt(2,0.5), y: 0 }, { x: 0, y: 0 }, { x: 1, y: 1 })
  // debugger
  let match_ids = (await mongoModels.TB21_luodian.aggregate([
    // {
    //   "$match": {
    //     "map_name": "Desert_Main"
    //   }
    // },
    {
      "$project": {
        "match_id": "$match_id",
        "_id": 0
      }
    },
    {
      "$group": {
        "_id": null,
        "distinct": {
          "$addToSet": "$$ROOT"
        }
      }
    },
    {
      "$unwind": {
        "path": "$distinct",
        "preserveNullAndEmptyArrays": false
      }
    },
    {
      "$replaceRoot": {
        "newRoot": "$distinct"
      }
    }
  ])).map(e => e.match_id);
  for (let match_id of match_ids) {
    let luodians = await mongoModels.TB21_luodian.find({
      match_id: match_id
    });
    let airline = await mongoModels.TB21_airline.findOne({
      match_id: match_id
    });
    for (let luodian of luodians) {
      // debugger
      let dis = distanceToLine(luodian['luodian'], airline['airline'][0], airline['airline'][1]);
      luodian['distance_to_airline'] = dis;
      let saved = await luodian.save();
      if (!saved) {
        // debugger
        console.log(match_id, luodian.player_name, "fail");
      }

    }
    // debugger
  }
  console.log("done")
  process.exit();


})